import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userinfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  },
  {
    path: '/reg',
    // webpack提供的import函数来路由懒加载导入组件
    // 即切换到哪个路径，再去加载对应的代码，首页加载的体积更小，加载更快
    component: () => import('@/views/register/index.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  }
]

const router = new VueRouter({
  routes
})

// 白名单，无需登录就可以访问的地址
const whiteList = ['/login', '/reg']
// 全局前置路由守卫
// 1、浏览器第一次打开项目页面，会触发一次全局前置路由守卫函数
// 2、通过token值判断用户是否登录
// 3、next()如果强制跳转，依然会执行全局前置路由守卫，造成死循环，所有需要再次判断
// 4、页面刷新，也会触发路由守卫，即从to和from的值一样
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    // 有token，说明登录了
    // 避免每一次跳转都会请求数据
    if (!store.state.userInfo.username) {
    // 本地有token，才去请求token值
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    if (whiteList.includes(to.path)) {
      // 未登录，可以访问的地址，则放行（路由全局前置守卫不会再次触发，而是匹配路由表，让组件挂载）
      next()
    } else {
      // 强制切换到登录路径上
      next('/login')
    }
  }
})

export default router
